package com.banfeiguanli.springboot.utils;

import com.banfeiguanli.springboot.common.Constant;
import com.banfeiguanli.springboot.exception.ServiceException;
import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

@Component
public class RsaUtil {
    public static volatile Map<String, String> keyMap = new HashMap<String, String>(2);
    /**
     * 获取公钥
     */
    public static String getPublicKey() {
        String publicKey = keyMap.get("public");
        if (publicKey == null) {
            // 加锁 防止多线程生产多个密钥
            synchronized (keyMap.getClass()) {
                if (publicKey == null) {
                    try {
                        genKeyPair();
                        publicKey = keyMap.get("public");
                    } catch (NoSuchAlgorithmException e) {
                        throw new ServiceException(Constant.CODE_1000, "获取公钥失败！");
                    }
                }
            }
        }
        return publicKey;
    }

    /**
     * 获取私钥
     */
    private static String getPrivateKey() {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        String privateKey = keyMap.get("private");
        if (privateKey == null) {
            throw new ServiceException(Constant.CODE_1001, "获取私钥失败！");
        }
        return privateKey;
    }

    /**
     * 随机生成密钥对
     *
     * @throws NoSuchAlgorithmException
     */
    public static void genKeyPair() throws NoSuchAlgorithmException {
        // KeyPairGenerator类用于生成公钥和私钥对，基于RSA算法生成对象
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
        // 初始化密钥对生成器，密钥大小为1024位
        keyPairGen.initialize(1024, new SecureRandom());
        // 生成一个密钥对，保存在keyPair中
        KeyPair keyPair = keyPairGen.generateKeyPair();
        // 得到私钥
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        // 得到公钥
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        String publicKeyString = new String(Base64.encodeBase64(publicKey.getEncoded()));
        // 得到私钥字符串
        String privateKeyString = new String(Base64.encodeBase64((privateKey.getEncoded())));
        // 将公钥和私钥保存到Map
        keyMap.put("public", publicKeyString);
        keyMap.put("private", privateKeyString);
    }

    /**
     * RSA公钥加密
     *
     * @param str       加密字符串
     * @return 密文
     * @throws Exception 加密过程中的异常信息
     */
//    public static String encrypt(String str) {
//        //获取公钥
//        String publicKey = getPublicKey();
//        //base64编码的公钥
//        byte[] decoded = Base64.decodeBase64(publicKey);
//        String outStr = "";
//        try {
//            RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
//            //RSA加密
//            Cipher cipher = Cipher.getInstance("RSA");
//            cipher.init(Cipher.ENCRYPT_MODE, pubKey);
//            outStr = Base64.encodeBase64String(cipher.doFinal(str.getBytes(StandardCharsets.UTF_8)));
//        }catch (Exception e){
//            System.out.println(e);
//        }
//        return outStr;
//    }

    /**
     * RSA私钥解密
     *
     * @param str 加密字符串
     * @return 明文
     * @throws Exception 解密失败
     */
    public static String decrypt(String str) {
        String outStr = "";
        //64位解码加密后的字符串
        byte[] inputByte = new byte[0];
        try {
            inputByte = Base64.decodeBase64(str.getBytes(StandardCharsets.UTF_8));
            //base64编码的私钥
            byte[] decoded = Base64.decodeBase64(getPrivateKey());
            RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
            //RSA解密
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, priKey);
            outStr = new String(cipher.doFinal(inputByte));
        } catch (Exception e) {
            throw new ServiceException(Constant.CODE_1002, "解密失败");
        }
        return outStr;
    }
}
